package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {

        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        //log.info(file.toString());

        //创建文件目录对象
        File f1 = new File(path);
        if (!f1.exists()){
            f1.mkdirs();
        }

        //获取原始文件名,这个是带后缀.jpg的
        String filename = file.getOriginalFilename();
        //随机文件名,防止文件名重复覆盖
        filename = UUID.randomUUID().toString()+filename;

        //将文件传入制定文件目录
        file.transferTo(new File(path+filename));

        //返回结果
        return R.success(filename);
    }

    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //输入流：获取文件的输入流
        FileInputStream is = new FileInputStream(path + name);
        //输出流：response的输出流
        ServletOutputStream os = response.getOutputStream();
        //输入流与输出流的拷贝
        IOUtils.copy(is, os);
    }


}
